package com.itheima.tanhua.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.tanhua.api.AnnouncementApi;
import com.itheima.tanhua.api.CommentApi;
import com.itheima.tanhua.api.FriendApi;
import com.itheima.tanhua.api.UserInfoApi;
import com.itheima.tanhua.autoconfig.template.HuanXinTemplate;
import com.itheima.tanhua.domain.Announcement;
import com.itheima.tanhua.domain.UserInfo;
import com.itheima.tanhua.enums.CommentType;
import com.itheima.tanhua.exception.BusinessException;
import com.itheima.tanhua.mongo.Comment;
import com.itheima.tanhua.mongo.Friend;
import com.itheima.tanhua.utils.Constants;
import com.itheima.tanhua.utils.UserHolder;
import com.itheima.tanhua.vo.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Lff
 * @date 2022/3/31
 */
@Service
public class MessagesService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private FriendApi friendApi;

    @Autowired
    private HuanXinTemplate hx;

    @DubboReference
    private AnnouncementApi announcementApi;

    @DubboReference
    private CommentApi commentApi;

    /**
     * 根据环信id查询用户详情信息
     *
     * @param hxUser
     * @return
     */
    public UserInfoVo findUserInfoByHx(String hxUser) {
        UserInfo userInfo = userInfoApi.findUserInfoByHxUser(hxUser);
        if (userInfo == null) {
            throw new BusinessException(ErrorResult.getHxUserInfoError());
        }
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);
        String age = userInfo.getAge() == null ? "" : userInfo.getAge().toString();
        userInfoVo.setAge(age);
        return userInfoVo;
    }

    /**
     * 同意好友申请
     *
     * @param friendId 朋友Id
     */
    public void agreeContacts(Long friendId) {
        //1.获取当前操作用户的id
        Long userId = UserHolder.getUser().getId();
        //2.在环信中添加好友绑定
        boolean result = hx.addContact(Constants.HX_USER_PREFIX + userId, Constants.HX_USER_PREFIX + friendId);
        if (!result) {
            throw new BusinessException(ErrorResult.createFriendRelationError());
        }
        //3.调用mongoApi添加好友关系
        friendApi.saveFriendRelation(userId, friendId);
    }

    public PageResult findContactsList(Integer page, Integer pagesize, String keyword) {
        //查询登录用户的所有好友即可
        //获取当前用户id
        Long id = UserHolder.getUser().getId();
        PageResult pr = friendApi.getUserFriendsById(id, page, pagesize);
        List<Friend> items = (List<Friend>) pr.getItems();
        //获取用户id
        List<Long> friendIds = items.stream().map(item -> item.getFriendId()).collect(Collectors.toList());
        //查
        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(keyword);
        Map<Long, UserInfo> userMap = userInfoApi.getUserInfosToMap(friendIds, userInfo);
        //填充返回值集合
        List<ContactVo> results = friendIds.stream().map(item -> {
            ContactVo init = ContactVo.init(userMap.get(item));
            return init;
        }).collect(Collectors.toList());
        pr.setItems(results);
        pr.setCounts(Long.valueOf(userMap.size()));
        return pr;
    }

    /**
     * 获取公告列表
     *
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult getAnnouncements(Integer page, Integer pagesize) {
        Page<Announcement> pages = announcementApi.findByPage(page, pagesize);
        if (CollUtil.isEmpty(pages.getRecords())) {
            return new PageResult(page, pagesize, 0l, null);
        }
        List<AnnouncementVo> result = pages.getRecords().stream().map(c -> {
            AnnouncementVo init = AnnouncementVo.init(c);
            return init;
        }).collect(Collectors.toList());

        PageResult pr = new PageResult(page, pagesize, pages.getTotal(), result);
        return pr;
    }

    /**
     * 查看喜欢列表
     *
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult getLoves(Integer page, Integer pagesize) {
        //获取当前登录用户id
        Long id = UserHolder.getUser().getId();
        List<Comment> comments = commentApi.getCommentList(page, pagesize, CommentType.LOVE.getType(), id);
        if (CollUtil.isEmpty(comments)) {
            return new PageResult(page, pagesize, 0l, null);
        }
        //根据id获取用户信息
        List<Long> ids = comments.stream().map(comment -> comment.getUserId()).collect(Collectors.toList());
        Map<Long, UserInfo> userMaps = userInfoApi.getUserInfosToMap(ids, null);
        List<CommentVo> result = comments.stream().map(comment ->
                        CommentVo.init(userMaps.get(comment.getUserId()), comment))
                .collect(Collectors.toList());
        return new PageResult(page, pagesize, Long.valueOf(result.size()), result);
    }


    /**
     * 查看点赞列表
     *
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult getLikes(Integer page, Integer pagesize) {
        //获取当前登录用户id
        Long id = UserHolder.getUser().getId();
        List<Comment> comments = commentApi.getCommentList(page, pagesize, CommentType.LIKE.getType(), id);
        if (CollUtil.isEmpty(comments)) {
            return new PageResult(page, pagesize, 0l, null);
        }
        //根据id获取用户信息
        List<Long> ids = comments.stream().map(comment -> comment.getUserId()).collect(Collectors.toList());
        Map<Long, UserInfo> userMaps = userInfoApi.getUserInfosToMap(ids, null);
        List<CommentVo> result = comments.stream().map(comment ->
                        CommentVo.init(userMaps.get(comment.getUserId()), comment))
                .collect(Collectors.toList());
        return new PageResult(page, pagesize, Long.valueOf(result.size()), result);
    }

    /**
     * 查看评论列表
     *
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult getComments(Integer page, Integer pagesize) {
        //获取当前登录用户id
        Long id = UserHolder.getUser().getId();
        List<Comment> comments = commentApi.getCommentList(page, pagesize, CommentType.COMMENT.getType(), id);
        if (CollUtil.isEmpty(comments)) {
            return new PageResult(page, pagesize, 0l, null);
        }
        //根据id获取用户信息
        List<Long> ids = comments.stream().map(comment -> comment.getUserId()).collect(Collectors.toList());
        Map<Long, UserInfo> userMaps = userInfoApi.getUserInfosToMap(ids, null);
        List<CommentVo> result = comments.stream().map(comment ->
                        CommentVo.init(userMaps.get(comment.getUserId()), comment))
                .collect(Collectors.toList());
        return new PageResult(page, pagesize, Long.valueOf(result.size()), result);
    }
}
